package com.huluobo.a2107mvpimdemo.contact.presenter;

import com.huluobo.a2107mvpimdemo.base.BasePresenter;
import com.huluobo.a2107mvpimdemo.bean.ContactListItemBean;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 联系人的P层
 * Created by LC on 2023/9/27.
 */
public class ContactPresenter extends BasePresenter<ContactContract.View> implements ContactContract.Presenter {

    @Override
    public void loadContact() {
        EMClient.getInstance().contactManager().aysncGetAllContactsFromServer(new EMValueCallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> value) {
                //先声明包含有首字符 是否显示首字符的自定义的bean的list
                List<ContactListItemBean> contactListItemBeans = new ArrayList<>();
                //给返回的数据排序
                Collections.sort(value);
                for (int i = 0; i < value.size(); i++) {
                    boolean showFirstLetter = false;
                    //第一个item肯定要显示首字符
                    //与上一个对比首字符,如果不同就显示
                    if (i == 0 || value.get(i).charAt(0) != value.get(i - 1).charAt(0)) {
                        showFirstLetter = true;
                    }
                    //首字符需要转换为大写
                    ContactListItemBean contactListItemBean = new ContactListItemBean(value.get(i),
                            Character.toUpperCase(value.get(i).charAt(0)), showFirstLetter);
                    contactListItemBeans.add(contactListItemBean);
                }
                if (isAttach()) {
                    getView().onLoadContactSuccess(contactListItemBeans);
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (isAttach()) {
                    getView().onLoadContactFailed(errorMsg);
                }
            }
        });
    }
}
